package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * /pub/user 公共访问的路径
 */

@Controller
@RequestMapping("/pub/user")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    /**
     * 登录功能
     * @return
     */
    @GetMapping("/toLogin")
    public String toLogin(){
        return "/user/login";
    }

    @PostMapping("/login")
    public String login(String username, String pwd, HttpSession session,Model model){
        User user = userService.login(username, pwd);
        if(user != null){
            session.setAttribute("user", user);
            return "redirect:/pri/student/findAll";
        }
        model.addAttribute("msg", "账号或密码错误");
        return "user/login";
    }

    /**
     * 注册功能
     * @param model
     * @return
     */
    @GetMapping("/toRegister")
    public String toRegister(Model model){
        model.addAttribute("user", new User());
        return "user/register";
    }

    @PostMapping("/register")
    public String register(User user, Model model){
        boolean flag = userService.register(user);
        if(flag){
            return "user/login";
        }
        model.addAttribute("msg", "命名不规范");
        return "user/register";

    }

    /**
     * 退出登录, 并且清除session会话
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        //清除session会话
        session.removeAttribute("user");
        return "index";
    }

    /**
     * 修改密码
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/toRevise")
    public String toRevise(HttpServletRequest request,Model model){
        Integer id = Integer.parseInt(request.getParameter("id"));
        User user = userService.findUserById(id);
        model.addAttribute("user", user);
        model.addAttribute("oldPwd",user.getPwd());
        return "user/revise";
    }

    @PostMapping("/revise")
    public String revise(User user,String oldPwd,Model model){

        User oldUser = userService.findByUserByPwd(user.getId(),oldPwd);
        if(oldUser != null){
            userService.revise(user);
            return "index";   //重新登录一下, 修改完密码
        }
        model.addAttribute("msg","旧密码不对");
        return "user/revise";
    }

}
